package ynu.edu.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ynu.edu.entity.User;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user")
public class UserController {

    private Random random = new Random();
    
    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/getUserById/{userId}")
    public User GetUserById(@PathVariable("userId") Integer userId){
        User user = new User();
        user.setUserId(userId);
        user.setUserName("小明 from " + serverPort);
        user.setPassWord("123456");
        return user;
    }
    
    /**
     * 负载均衡演示接口 - 返回当前服务实例信息
     */
    @GetMapping("/instance-info")
    public Map<String, Object> getInstanceInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("service_name", "provider-service");
        info.put("port", serverPort);
        info.put("instance_id", "provider-service-" + serverPort);
        info.put("timestamp", System.currentTimeMillis());
        info.put("message", "Hello from Provider Service on port " + serverPort);
        
        System.out.println("🔀 负载均衡演示 - Provider-" + serverPort + " 处理请求");
        return info;
    }
    
    /**
     * 测试端点 - 随机失败用于触发熔断器
     */
    @GetMapping("/test-error/{userId}")
    public User testError(@PathVariable("userId") Integer userId) throws Exception {
        // 60% 概率抛出异常
        if (random.nextInt(100) < 60) {
            System.out.println("🔥 Provider-" + serverPort + " 模拟异常: userId=" + userId);
            throw new RuntimeException("模拟服务异常 - Provider " + serverPort);
        }
        
        // 20% 概率延迟响应
        if (random.nextInt(100) < 20) {
            System.out.println("⏰ Provider-" + serverPort + " 模拟延迟: userId=" + userId);
            Thread.sleep(4000); // 4秒延迟，触发超时
        }
        
        User user = new User();
        user.setUserId(userId);
        user.setUserName("测试用户 from " + serverPort);
        user.setPassWord("123456");
        System.out.println("✅ Provider-" + serverPort + " 正常响应: userId=" + userId);
        return user;
    }
    
    /**
     * 慢响应端点 - 用于测试超时
     */
    @GetMapping("/slow/{userId}")
    public User slowResponse(@PathVariable("userId") Integer userId) throws Exception {
        // 模拟慢响应
        Thread.sleep(5000);
        
        User user = new User();
        user.setUserId(userId);
        user.setUserName("慢响应用户 from " + serverPort);
        user.setPassWord("123456");
        return user;
    }
}
